<!-- 识别关键字列表 -->
<template>
	<div class="distin-identity-key-container">
		<!-- 数据列表 -->
		<YdTable
			:formData="searchFormData"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="searchHandler"
			@currentChangeHandler="handleQuery"
			@sortChangeHandler="handleQuery"
			@selectionChangeHandler="handlerSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog v-model="dialog.addOrUpdate.open" :title="dialog.addOrUpdate.title" width="600px" append-to-body center>
			<el-form ref="addOrUpdateForm" :model="dialog.addOrUpdate.form" :rules="dialog.addOrUpdate.rule" label-width="120px">
				<el-form-item label="来源" prop="source">
					<el-select v-model="dialog.addOrUpdate.form.source" placeholder="请选择来源" style="width: 100%">
						<el-option v-for="(option, index) in options.sourceOptions" :key="index" :label="option.label" :value="option.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="关键字" prop="keyword">
					<el-input v-model="dialog.addOrUpdate.form.keyword" maxlength="100" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item label="识别标识符" prop="identifier">
					<el-input v-model="dialog.addOrUpdate.form.identifier" maxlength="100" placeholder="请输入识别标识符"></el-input>
				</el-form-item>
				<el-form-item label="匹配串" prop="matchStr">
					<el-input v-model="dialog.addOrUpdate.form.matchStr" maxlength="1000" placeholder="请输入匹配串"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" :loading="dialog.addOrUpdate.btnLoading" @click="handlerSubmit">确 定</el-button>
					<el-button @click="closeAddOrUpdateDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="DistinIdentityKey" lang="ts">
import { identityKeyOptions } from '@/utils/management/commonOptions';
import { list, add, edit, remove } from '@/api/management/IndicatorManage/proprietaryIndicatorManage/identityKey';
import { ref, reactive, onMounted, watch } from 'vue';
import useCurrentInstance from '@/utils/useCurrentInstance';

const { proxy } = useCurrentInstance();

const props = defineProps({
	resource: {
		type: Object,
		default: () => {
			return {};
		},
	},
});

const addOrUpdateForm = ref();
// 选项
let options = reactive(identityKeyOptions());
// 搜索表单数据
let searchFormData = reactive<FormModelType>({
	pageSize: 10,
	pageNum: 1,
	orderByColumn: '',
	isAsc: '',
});
// 列表配置
let tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '来源',
			prop: 'source',
			width: 120,
			showOverFlowToolTip: true,
		},
		{
			label: '关键字',
			prop: 'keyword',
			width: 120,
			showOverFlowToolTip: true,
		},
		{
			label: '识别标识符',
			prop: 'identifier',
			showOverFlowToolTip: true,
		},
		{
			label: '匹配串',
			prop: 'matchStr',
			showOverFlowToolTip: true,
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['resource:identity:add'], handler: () => handlerAdd(addFilter) },
		{ name: '修改', icon: 'yd-icon-edit', disable: 'single', permi: ['resource:identity:edit'], handler: () => handlerEdit() },
		{ name: '删除', icon: 'yd-icon-delete', disable: 'multiple', permi: ['resource:identity:delete'], handler: () => handlerDelete() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = reactive({
	data: [],
});
// 选择的行数据ids
const selectedIds = ref();
// 选择的行数据
const selected = ref();
let dialog = reactive<anyObj>({
	addOrUpdate: {
		// 打开状态
		open: false,
		// 标题
		title: '',
		// 表单数据
		form: {},
		// 按钮加载中状态
		btnLoading: false,
		// 表单校验规则
		rule: {
			source: [{ required: true, message: '来源必选', trigger: 'change' }],
			matchStr: [{ required: true, message: '匹配串不能为空', trigger: 'blur' }],
		},
	},
});

watch(
	() => props.resource,
	(newval) => {
		console.log('watch', props.resource);
		searchFormData.resourceCode = props.resource.resourceCode;
		searchFormData.identifyStr = props.resource.identifyStr;
		handleQuery();
	},
	{ deep: true }
);

onMounted(() => {
	// searchFormData.resourceCode = props.resource.resourceCode;
	// searchFormData.identifyStr = props.resource.identifyStr;
	// handleQuery();
});

/**
 * 关闭新增或修改弹出层
 */
function closeAddOrUpdateDialog() {
	dialog.addOrUpdate.open = false;
}
/**
 * 选择行数据
 */
function handlerSelectionChange(selects: any) {
	selectedIds.value = selects.map((item: any) => item.id);
	selected.value = selects;
}

function searchHandler() {
	tableConfig.pagination!.pageNum = 1;
	handleQuery();
}

/**
 * 搜索
 */
function handleQuery() {
	tableConfig.loading = true;
	list(searchFormData).then((res: ApiResponse) => {
		tableConfig.loading = false;
		if (res.code !== 0) {
			return;
		}
		if (res.data !== null) {
			tableData.data = res.data.records;
			tableConfig.pagination!.total = res.data.total;
		}
	});
}
/**
 * 表单提交
 */
function handlerSubmit() {
	if (dialog.addOrUpdate.title === '新增') {
		handlerAdd();
	} else {
		handlerEdit();
	}
}
/**
 * 新增
 */
function handlerAdd(filter?: any) {
	let sign;
	if (typeof filter === 'function' && !(sign = filter())) {
		return;
	}
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 表单重置
		if (sign !== 'SET_FORM') {
			dialog.addOrUpdate.form = {};
			addOrUpdateForm.value?.resetFileds();
		}
		// 标题
		dialog.addOrUpdate.title = '新增';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		return;
	}
	// 校验参数
	addOrUpdateForm.value?.validate((valid: any) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnLoading = true;
		add(dialog.addOrUpdate.form).then((res: ApiResponse) => {
			dialog.addOrUpdate.btnLoading = false;
			if (res.code !== 0) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			searchFormData.pageNum = 1;
			handleQuery();
			// 提示
			proxy.$modal.msgSuccess('新增成功！');
		});
	});
}
/**
 * 修改
 */
function handlerEdit() {
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 数据回显，数据需要拷贝一下
		const d = JSON.parse(JSON.stringify(selected.value[0]));
		dialog.addOrUpdate.form = d;
		// 标题
		dialog.addOrUpdate.title = '修改';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		return;
	}
	// 校验参数
	addOrUpdateForm.value?.validate((valid: any) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnDisabled = true;
		edit(dialog.addOrUpdate.form).then((res: ApiResponse) => {
			dialog.addOrUpdate.btnDisabled = false;
			if (res.code !== 0) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			searchFormData.pageNum = 1;
			handleQuery();
			// 提示
			proxy.$modal.msgSuccess('修改成功！');
		});
	});
}
/**
 * 删除
 */
function handlerDelete() {
	proxy.$modal
		.confirm('是否确认删除所选项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return remove(selectedIds.value);
		})
		.then(() => {
			// 刷新列表 计算是否要查询上一页的数据
			if (tableConfig.pagination!.total && searchFormData.pageSize) {
				// 删除后的总条数
				let totalCount = tableConfig.pagination!.total - selectedIds.value.length;
				// 计算删除后的总页数
				let totalPage = Math.ceil(totalCount / searchFormData.pageSize);
				// 如果删除后的总页数小于1, 置为1
				totalPage = totalPage < 1 ? 1 : totalPage;
				// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
				searchFormData.pageNum = searchFormData.pageNum! > totalPage ? totalPage : searchFormData.pageNum;
			} else {
				searchFormData.pageNum = 1;
			}
			handleQuery();
			// 提示
			proxy.$modal.msgSuccess('删除成功！');
		});
}
// 新增过滤器
function addFilter() {
	dialog.addOrUpdate.form = {
		resourceCode: props.resource.resourceCode,
		identifier: props.resource.identifier,
	};
	return 'SET_FORM';
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped></style>
